package com.pdf.utils;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author PC
 * @version 1.0
 * @description: TODO
 * @date 2024/7/9 9:36
 */
@Slf4j
public class WordToPdfUtil {
    /**
     * 获取aspose证书
     */
    private static boolean getLicense() {
        boolean result = false;
        InputStream is = null;
        try {
            Resource resource = new ClassPathResource("License.xml");
            is = resource.getInputStream();
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * @description:  word转pdf
     * @param: wordPath word路径
     * @param: pdfPath pdf路径
     * @return: java.io.File 返回文件
     * @author liangalong
     * @date: 2024/7/9 9:52
     * */
    public static File docToPdf(String wordPath, String pdfPath) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return new File(pdfPath);
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            // 新建一个空白pdf文档
            File file = new File(pdfPath);
            os = new FileOutputStream(file);
            // inPath是将要被转化的word文档
            Document doc = new Document(wordPath);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互转换
            doc.save(os, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            // 转化用时
            log.info("word转换pdf成功，共耗时：" + ((now - old) / 1000.0) + "秒");
            return file;
        } catch (Exception e) {
            log.error("word转pdf失败:" + e.getMessage());
            return new File(pdfPath);
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
